package postgres

import (
	"auth/model"
	"auth/model/entity"
	"gorm.io/gorm"
)

var AuthorityMenu = &authorityMenu{}

type authorityMenu struct{}

func (a *authorityMenu) SetMenuAuthority(authorityId int64, auth []*entity.AuthorityMenu) error {
	return db.Transaction(func(tx *gorm.DB) error {
		txErr := tx.Delete(&entity.AuthorityMenu{}, "authority_id=?", authorityId).Error
		if txErr != nil {
			return txErr
		}
		if auth == nil {
			return nil
		}
		txErr = tx.Create(&auth).Error
		if txErr != nil {
			return txErr
		}
		return nil
	})
}

func (a *authorityMenu) Create(m *entity.AuthorityMenu) error {
	err := db.Create(m).Error
	return err
}

func (a *authorityMenu) FindByAuthorityIds(authorityIds []int64) ([]*entity.AuthorityMenu, error) {
	var authorityMenus []*entity.AuthorityMenu
	err := db.Model(&entity.AuthorityMenu{}).Find(&authorityMenus, "authority_id in (?)", authorityIds).Error
	return authorityMenus, err
}

func (a *authorityMenu) DeleteByAuthorityId(id int64) error {
	return db.Delete(&entity.AuthorityMenu{}, "authority_id=?", id).Error
}

func (a *authorityMenu) DeleteByMenuId(id int64) error {
	return db.Delete(&entity.AuthorityMenu{}, "menu_id =?", id).Error
}

func (a *authorityMenu) List(in *model.AuthorityMenuListRequest) (int, []*entity.AuthorityMenu, error) {
	var (
		q              = db.Model(&entity.AuthorityMenu{})
		err            error
		total          int64
		authorityMenus []*entity.AuthorityMenu
	)

	if err = q.Count(&total).Error; err != nil {
		return 0, nil, err
	}
	if err = q.Limit(in.Size).Offset((in.Index - 1) * in.Size).Find(&authorityMenus).Error; err != nil {
		return 0, nil, err
	}
	return int(total), authorityMenus, nil
}
